package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.entity.*;
import com.example.HaiDLaobackend.service.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/member")
public class MemberController {

	private final UserService userService;
	private final CouponService couponService;
	private final UserCouponService userCouponService;
	private final MemberLevelCouponService memberLevelCouponService;
	private final UserMemberCouponService userMemberCouponService;

	public MemberController(UserService userService, CouponService couponService,
			UserCouponService userCouponService, MemberLevelCouponService memberLevelCouponService,
			UserMemberCouponService userMemberCouponService) {
		this.userService = userService;
		this.couponService = couponService;
		this.userCouponService = userCouponService;
		this.memberLevelCouponService = memberLevelCouponService;
		this.userMemberCouponService = userMemberCouponService;
	}

	@GetMapping("/info")
	public ApiResponse<Map<String, Object>> getMemberInfo(
			@RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
		if (currentUserId == null) {
			return ApiResponse.error(401, "未登录");
		}

		UserEntity user = userService.getById(currentUserId);
		if (user == null) {
			return ApiResponse.error(404, "用户不存在");
		}

		Map<String, Object> result = new HashMap<>();
		String memberLevel = user.getMemberLevel() != null ? user.getMemberLevel() : "NONE";
		result.put("memberLevel", memberLevel);
		result.put("isMember", !"NONE".equals(memberLevel));

		// 获取所有等级的优惠券列表
		List<Map<String, Object>> levelCoupons = new ArrayList<>();
		String[] levels = { "BRONZE", "SILVER", "GOLD", "PLATINUM" };
		String[] levelNames = { "青铜", "白银", "黄金", "黑金" };

		for (int i = 0; i < levels.length; i++) {
			String level = levels[i];
			String levelName = levelNames[i];

			// 获取该等级的优惠券
			List<MemberLevelCouponEntity> mlCoupons = memberLevelCouponService.list(
					new LambdaQueryWrapper<MemberLevelCouponEntity>()
							.eq(MemberLevelCouponEntity::getMemberLevel, level)
							.eq(MemberLevelCouponEntity::getStatus, 1)
							.orderByAsc(MemberLevelCouponEntity::getSortOrder));

			List<Map<String, Object>> coupons = new ArrayList<>();
			for (MemberLevelCouponEntity mlc : mlCoupons) {
				CouponEntity coupon = couponService.getById(mlc.getCouponId());
				if (coupon == null || coupon.getStatus() == null || coupon.getStatus() == 0) {
					continue;
				}

				// 检查用户是否已领取
				boolean claimed = userMemberCouponService.count(
						new LambdaQueryWrapper<UserMemberCouponEntity>()
								.eq(UserMemberCouponEntity::getUserId, currentUserId)
								.eq(UserMemberCouponEntity::getMemberLevelCouponId, mlc.getId())) > 0;

				// 检查用户等级是否达到
				boolean canClaim = canClaimLevel(level, memberLevel);

				Map<String, Object> couponMap = new HashMap<>();
				couponMap.put("id", coupon.getId());
				couponMap.put("memberLevelCouponId", mlc.getId());
				couponMap.put("name", coupon.getName());
				couponMap.put("description", coupon.getDescription());
				couponMap.put("discountAmount", coupon.getDiscountAmount());
				couponMap.put("thresholdAmount", coupon.getThresholdAmount());
				couponMap.put("claimed", claimed);
				couponMap.put("canClaim", canClaim && !claimed);
				coupons.add(couponMap);
			}

			Map<String, Object> levelMap = new HashMap<>();
			levelMap.put("level", level);
			levelMap.put("levelName", levelName);
			levelMap.put("coupons", coupons);
			levelCoupons.add(levelMap);
		}

		result.put("levelCoupons", levelCoupons);
		return ApiResponse.ok(result);
	}

	@PostMapping("/join")
	@Transactional
	public ApiResponse<Map<String, Object>> joinMember(
			@RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
		if (currentUserId == null) {
			return ApiResponse.error(401, "未登录");
		}

		UserEntity user = userService.getById(currentUserId);
		if (user == null) {
			return ApiResponse.error(404, "用户不存在");
		}

		// 如果已经是会员，返回当前等级
		if (user.getMemberLevel() != null && !"NONE".equals(user.getMemberLevel())) {
			Map<String, Object> result = new HashMap<>();
			result.put("memberLevel", user.getMemberLevel());
			return ApiResponse.ok(result);
		}

		// 加入会员，默认等级为青铜
		user.setMemberLevel("BRONZE");
		userService.updateById(user);

		Map<String, Object> result = new HashMap<>();
		result.put("memberLevel", "BRONZE");
		return ApiResponse.ok(result);
	}

	@PostMapping("/coupon/claim")
	@Transactional
	public ApiResponse<CouponEntity> claimMemberCoupon(
			@RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
			@RequestParam Long memberLevelCouponId) {
		if (currentUserId == null) {
			return ApiResponse.error(401, "未登录");
		}

		UserEntity user = userService.getById(currentUserId);
		if (user == null) {
			return ApiResponse.error(404, "用户不存在");
		}

		String memberLevel = user.getMemberLevel() != null ? user.getMemberLevel() : "NONE";
		if ("NONE".equals(memberLevel)) {
			return ApiResponse.error(400, "您还不是会员，无法领取会员优惠券");
		}

		// 获取会员等级优惠券
		MemberLevelCouponEntity mlc = memberLevelCouponService.getById(memberLevelCouponId);
		if (mlc == null || mlc.getStatus() == null || mlc.getStatus() == 0) {
			return ApiResponse.error(404, "优惠券不存在");
		}

		// 检查用户等级是否达到
		if (!canClaimLevel(mlc.getMemberLevel(), memberLevel)) {
			return ApiResponse.error(400, "您的会员等级不足，无法领取该优惠券");
		}

		// 检查是否已领取
		long count = userMemberCouponService.count(
				new LambdaQueryWrapper<UserMemberCouponEntity>()
						.eq(UserMemberCouponEntity::getUserId, currentUserId)
						.eq(UserMemberCouponEntity::getMemberLevelCouponId, memberLevelCouponId));
		if (count > 0) {
			return ApiResponse.error(400, "您已领取过该优惠券");
		}

		// 获取优惠券信息
		CouponEntity coupon = couponService.getById(mlc.getCouponId());
		if (coupon == null || coupon.getStatus() == null || coupon.getStatus() == 0) {
			return ApiResponse.error(404, "优惠券不存在");
		}

		// 创建用户优惠券
		UserCouponEntity userCoupon = new UserCouponEntity();
		userCoupon.setUserId(currentUserId);
		userCoupon.setCouponId(coupon.getId());
		userCoupon.setStatus(0);
		userCoupon.setAcquiredAt(LocalDateTime.now());
		userCouponService.save(userCoupon);

		// 记录领取记录
		UserMemberCouponEntity record = new UserMemberCouponEntity();
		record.setUserId(currentUserId);
		record.setMemberLevelCouponId(memberLevelCouponId);
		userMemberCouponService.save(record);

		return ApiResponse.ok(coupon);
	}

	// 判断用户等级是否可以领取某个等级的优惠券
	private boolean canClaimLevel(String requiredLevel, String userLevel) {
		if ("NONE".equals(userLevel)) {
			return false;
		}
		String[] levels = { "BRONZE", "SILVER", "GOLD", "PLATINUM" };
		int requiredIndex = -1;
		int userIndex = -1;
		for (int i = 0; i < levels.length; i++) {
			if (levels[i].equals(requiredLevel)) {
				requiredIndex = i;
			}
			if (levels[i].equals(userLevel)) {
				userIndex = i;
			}
		}
		return userIndex >= requiredIndex;
	}
}

